package com.damai.proxy;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.util.ByteArrayBuffer;

import com.citywithincity.utils.IoUtil;
import com.citywithincity.utils.MapUtil;
import com.citywithincity.utils.RequestUtil;
import com.damai.utils.LogUtil;

public class ProxyParamAction extends ProxyAction {
	/**
	 * 
	 */

	public static HttpURLConnection createConnection(String url) throws IOException {
		URL netUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) netUrl.openConnection();

		connection.setConnectTimeout(10000);
		connection.setReadTimeout(10000);
		connection.setUseCaches(false);
		connection.setDoInput(true);

		return connection;
	}

	public static HttpURLConnection postData(HttpURLConnection connection, byte[] content,
			Map<String, String> extraHeaders) throws IOException {
		connection.setDoOutput(true);
		connection.setRequestMethod("POST");

		connection.setUseCaches(false);
		// connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setRequestProperty("Content-Length", String.valueOf(content.length));
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		if (extraHeaders != null) {
			for (Entry<String, String> entry : extraHeaders.entrySet()) {
				connection.setRequestProperty(entry.getKey(), entry.getValue());
			}
			if (extraHeaders.containsKey("attach")) {
				connection.setChunkedStreamingMode(1024);
			}
		}

		OutputStream out = null;
		try {
			// write
			out = new DataOutputStream(connection.getOutputStream());
			out.write(content);
			out.flush();
		} finally {
			IoUtil.close(out);
		}
		return connection;
	}


	private static byte[] read(InputStream stream) throws IOException {

		ByteArrayBuffer buffer = new ByteArrayBuffer(0);
		int len = 0;
		byte[] bytes = new byte[1024];
		while ((len = stream.read(bytes)) > 0) {
			buffer.append(bytes, 0, len);
		}
		return buffer.buffer();
	}
	
	private static byte[] read(HttpServletRequest request) throws IOException {
		Map<String, String> data = RequestUtil.requestToMap(request);
		String queryString = MapUtil.toQueryString(data);
		LogUtil.log("recv : %s", queryString);
		return  queryString.getBytes("utf-8");
	}

	private static Map<String, String> getHeaders(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String key = headerNames.nextElement();
			String value = request.getHeader(key);
			map.put(key, value);
		}
		return map;
	}
	
	
	
	
	public ProxyParamAction(String key) {
		super(key);
	}
	
	

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String queryString = request.getQueryString();
		String url = getProxyUrl() + queryString.substring(getPosition());///////////////////
		HttpURLConnection connection = createConnection(url);
		
		
		Map<String, String> headers = getHeaders(request);
		
		/*byte[] readed = read(request.getInputStream());
		if(readed==null || readed.length == 0){
			readed = read(request);
		}*/
		
		byte[] readed = read(request);
		postData(connection,readed , headers);
		
		
		byte[] respData = read(connection.getInputStream());
		//session
		//connection.getHeaderFields();
		for (Entry<String, List<String>> e : connection.getHeaderFields().entrySet()) {
			if(e.getKey()==null)continue;
			response.setHeader(e.getKey(), e.getValue().get(0));
			
		}
		
		
		
		response.getOutputStream().write(respData);
	}

	

}
